// 含有嵌套的字符串解码
// 测试链接 : https://leetcode.cn/problems/decode-string/
public class DecodeString {
    public int where;
    public String decodeString(String s) {
        where = 0;

        return func(s.toCharArray(), 0);
    }

    public String func(char[] s, int i){
        StringBuilder sb = new StringBuilder();
        int cnt = 0;  //记录添加的次数

        while(i < s.length && s[i] != ']' ) {
            if( (s[i] >= 'a' && s[i] <= 'z')  || (s[i] >= 'A' && s[i] <= 'Z')) {
                sb.append(s[i++]);
            }else if( s[i] != '['){
                cnt = cnt * 10 + s[i++] - '0';
            }else{
                sb.append(get(cnt, func(s,i+1)));
                i = where + 1;
                cnt = 0;
            }
        }
        where = i ;
        return sb.toString();
    }

    public String get(int cnt, String temp){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < cnt; i++){
            sb.append(temp);
        }
        return sb.toString();
    }
}
